import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { connect } from 'react-redux' //连接
import { bindActionCreators } from 'redux' //绑定action创建函数
import { hashHistory } from 'react-router'

import * as storeActionsFromFile from '../../../actions/store'

import BuyAndStore from '../../../components/BuyAndStore/index.jsx';
class Buy extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state={
        	isStore:false//是否已收藏
        }
        this.buyHandle = this.buyHandle.bind(this);
        this.storeHandle = this.storeHandle.bind(this)
    }
    render() {
    	let {isStore} = this.state;
    	let {buyHandle,storeHandle} = this;
        return (
            <BuyAndStore
            	{...{
            		isStore:isStore,
            		buyHandle:buyHandle,
            		storeHandle:storeHandle
            	}}
            />
        )
    }
    componentDidMount() {
    	//验证当前商户是否已经被收藏
    	this.checkStoreState()
    }
    //购买事件
    buyHandle(){
    	//验证登录
    	let loginFlag = this.loginCheck();
    	if(!loginFlag){
    		return
    	}
    	//购买流程（此处省略）
    	//跳转到用户主页
    	hashHistory.push('/User')
    }
    //收藏事件
    storeHandle(){
    	//验证登录
    	let loginFlag = this.loginCheck();
    	if(!loginFlag){
    		return
    	}
    	let id = this.props.id;
    	let storeActions = this.props.storeActions;
    	if(this.state.isStore){
    		//当前商户已经被收藏了，点击就会取消收藏；
    		storeActions.rm({id:id})
    	}else{
    		//当前商户尚未被收藏，点击时就是要收藏
    		storeActions.add({id:id})
    	}
    	//修改收藏状态
    	this.setState({
    		isStore:!this.state.isStore 
    	});
    		
    }
    //验证当前商户是否已经被收藏
    checkStoreState(){
    	let id = this.props.id;
    	let store = this.props.store;
    	//some：只要有一个满足就可以了
    	store.some((item)=>{
    		if(item.id ===id){
    			//被收藏了
    			this.setState({
    				isStore:true 
    			});
    			//跳出循环
    			return true
    		}
    	})
    }
    //验证登录
    loginCheck(){
    	let {id} = this.props;
    	//redux中
    	let userinfo = this.props.userinfo;
    	if(!userinfo.username){
    		//跳转登录页面(登录成功后立刻跳转回来)
    		hashHistory.push('/Login/' + encodeURIComponent('/detail/' + id))
    		return false
    	}
    	return true
    }
    
}
//----------------------------连接redux-----------------------------
function mapStateToProps(state) {
    return {
        userinfo: state.userinfo,
        store:state.store
    }
}

function mapDispatchToProps(dispatch) {
    return {
        storeActions:bindActionCreators(storeActionsFromFile,dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Buy)